package com.aiot.config;

import com.aiot.handler.VideoWebSocketHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

@Configuration
@EnableWebSocket
public class RawWebSocketConfig implements WebSocketConfigurer {

    private final VideoWebSocketHandler handler;

    public RawWebSocketConfig(VideoWebSocketHandler handler) {
        this.handler = handler;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 注册两个端点：/video/sender 和 /video/viewer
        registry.addHandler(handler, "/video/sender", "/video/viewer")
                .setAllowedOrigins("*");
    }

    /**
     * 放大容器的单条消息缓冲区 & 发送超时
     */
    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(2 * 1024 * 1024);   // 2MB
        container.setMaxBinaryMessageBufferSize(2 * 1024 * 1024); // 2MB
        container.setAsyncSendTimeout(60_000L);                   // 60s
        container.setMaxSessionIdleTimeout(0L);                   // 不自动踢
        return container;
    }
}
